const fs = require('fs');
const path = require('path');
const utils = require('../../utils/utils');
const sqlPool = require('../../DB/sqlPool');
const sqlConfig = require('../../DB/sqlConfig');
const notificationConfig = require('../../config/notification');
const moment = require('moment');

/**
 * 初始化设置表
 */
async function initSettingsTable() {
    try {
        // 创建系统设置表
        await sqlPool.queryData(`
            CREATE TABLE IF NOT EXISTS system_settings (
                id INT AUTO_INCREMENT PRIMARY KEY,
                category VARCHAR(50) NOT NULL COMMENT '设置类别',
                key_name VARCHAR(100) NOT NULL COMMENT '设置键名',
                key_value TEXT COMMENT '设置值',
                description VARCHAR(255) COMMENT '描述',
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                UNIQUE KEY (category, key_name)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统设置表';
        `);
        
        // 检查是否已有邮箱设置
        const { rows: emailSettings } = await sqlPool.queryData(
            `SELECT * FROM system_settings WHERE category = 'email'`
        );
        
        if (emailSettings.length === 0) {
            // 初始化邮箱设置
            await sqlPool.queryData(`
                INSERT INTO system_settings 
                (category, key_name, key_value, description) VALUES
                ('email', 'host', ?, '邮件服务器地址'),
                ('email', 'port', ?, '邮件服务器端口'),
                ('email', 'secure', ?, '是否使用SSL'),
                ('email', 'auth_user', ?, '邮箱账号'),
                ('email', 'auth_pass', ?, '邮箱密码'),
                ('email', 'from', ?, '发件人名称')
            `, [
                notificationConfig.email.host,
                notificationConfig.email.port.toString(),
                notificationConfig.email.secure ? '1' : '0',
                notificationConfig.email.auth.user,
                notificationConfig.email.auth.pass,
                notificationConfig.email.from
            ]);
        }
        
        // 检查是否已有短信设置
        const { rows: smsSettings } = await sqlPool.queryData(
            `SELECT * FROM system_settings WHERE category = 'sms'`
        );
        
        if (smsSettings.length === 0) {
            // 初始化短信设置
            await sqlPool.queryData(`
                INSERT INTO system_settings 
                (category, key_name, key_value, description) VALUES
                ('sms', 'accessKeyId', ?, '阿里云AccessKey ID'),
                ('sms', 'accessKeySecret', ?, '阿里云AccessKey Secret'),
                ('sms', 'signName', ?, '短信签名'),
                ('sms', 'templateCode_register', ?, '注册验证码模板ID'),
                ('sms', 'templateCode_login', ?, '登录验证码模板ID'),
                ('sms', 'templateCode_reset', ?, '重置密码验证码模板ID')
            `, [
                notificationConfig.aliyunSMS.accessKeyId,
                notificationConfig.aliyunSMS.accessKeySecret,
                notificationConfig.aliyunSMS.signName,
                notificationConfig.aliyunSMS.templateCode.register,
                notificationConfig.aliyunSMS.templateCode.login,
                notificationConfig.aliyunSMS.templateCode.resetPwd
            ]);
        }
        
        return true;
    } catch (error) {
        console.error('初始化设置表失败:', error);
        return false;
    }
}

// 初始化设置表
initSettingsTable().catch(console.error);

/**
 * 获取所有系统设置
 */
async function getSettings(req, res) {
    try {
        const { category } = req.query;
        
        let sql = `SELECT * FROM system_settings`;
        const params = [];
        
        if (category) {
            sql += ` WHERE category = ?`;
            params.push(category);
        }
        
        sql += ` ORDER BY category, key_name`;
        
        const { rows } = await sqlPool.queryData(sql, params);
        
        // 按类别分组
        const groupedSettings = {};
        rows.forEach(setting => {
            if (!groupedSettings[setting.category]) {
                groupedSettings[setting.category] = {};
            }
            
            // 屏蔽敏感信息
            if (setting.key_name === 'auth_pass' || setting.key_name === 'accessKeySecret') {
                setting.key_value = setting.key_value ? '******' : '';
            }
            
            groupedSettings[setting.category][setting.key_name] = setting;
        });
        
        return res.json(utils.SuccessResponse(groupedSettings));
    } catch (error) {
        console.error('获取系统设置失败:', error);
        return res.json(utils.ErrorResponse('获取系统设置失败'));
    }
}

/**
 * 更新系统设置
 */
async function updateSettings(req, res) {
    try {
        const { category, settings } = req.body;
        
        if (!category || !settings || typeof settings !== 'object') {
            return res.json(utils.ErrorResponse('参数错误'));
        }
        
        // 获取用户token
        const token = req.headers['authorization'] || req.headers['Authorization'];
        
        // 记录操作日志
        const operationLog = {
            operat_type: utils.OPERATION_TYPE.UPDATE,
            token: token,
            ip: req.ip || req.connection.remoteAddress,
            creat_time: parseInt(moment().format('x')),
            content: `更新${category}设置`,
            browser: (req.headers['user-agent'] || '').substring(0, 50),
            os: '',
            device: ''
        };
        
        for (const key in settings) {
            const value = settings[key];
            
            // 更新设置
            await sqlPool.queryData(
                `UPDATE system_settings SET key_value = ? WHERE category = ? AND key_name = ?`,
                [value, category, key]
            );
        }
        
        // 添加操作日志
        await sqlPool.queryData(
            `INSERT INTO ${sqlConfig.configureName.OPERATION_LOG} SET ?`,
            operationLog
        );
        
        // 更新配置文件
        await updateConfigFile();
        
        return res.json(utils.SuccessResponse('设置更新成功'));
    } catch (error) {
        console.error('更新系统设置失败:', error);
        return res.json(utils.ErrorResponse('更新系统设置失败'));
    }
}

/**
 * 更新配置文件
 */
async function updateConfigFile() {
    try {
        // 获取所有设置
        const { rows } = await sqlPool.queryData(
            `SELECT * FROM system_settings ORDER BY category, key_name`
        );
        
        // 按类别分组
        const config = {
            email: {
                auth: {}
            },
            aliyunSMS: {
                templateCode: {}
            }
        };
        
        rows.forEach(setting => {
            const { category, key_name, key_value } = setting;
            
            if (category === 'email') {
                if (key_name === 'auth_user') {
                    config.email.auth.user = key_value;
                } else if (key_name === 'auth_pass') {
                    config.email.auth.pass = key_value;
                } else if (key_name === 'secure') {
                    config.email.secure = key_value === '1';
                } else if (key_name === 'port') {
                    config.email.port = parseInt(key_value, 10);
                } else {
                    config.email[key_name] = key_value;
                }
            } else if (category === 'sms') {
                if (key_name.startsWith('templateCode_')) {
                    const purpose = key_name.replace('templateCode_', '');
                    config.aliyunSMS.templateCode[purpose] = key_value;
                } else {
                    config.aliyunSMS[key_name] = key_value;
                }
            }
        });
        
        // 更新配置文件
        const configPath = path.resolve(__dirname, '../../config/notification.js');
        const configContent = `module.exports = ${JSON.stringify(config, null, 4)};`;
        
        fs.writeFileSync(configPath, configContent);
        
        return true;
    } catch (error) {
        console.error('更新配置文件失败:', error);
        return false;
    }
}

module.exports = {
    getSettings,
    updateSettings
}; 